package controller;

import dao.UserDao;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import model.User;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method") == null ? "" : request.getParameter("method");
        UserDao userDao = new UserDao();
        // 登录
        if ("login".equals(method)) {
            User user = (User) request.getAttribute("u2");
            try {
                if (userDao.Login(user)) {
                    request.getSession().setAttribute("Username", user.getName());
                    response.sendRedirect("./index.jsp");
                } else {
                    request.setAttribute("error", "请检查用户名和密码是否正确");
                    ServletContext servletContext = this.getServletContext();
                    RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/index.jsp");
                    requestDispatcher.forward(request, response);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        // 注册
        if ("reg".equals(method)) {
            User user = (User) request.getAttribute("u3");
            RequestDispatcher requestDispatcher;
            ServletContext servletContext = this.getServletContext();
            if (userDao.regUser(user)) {
                request.setAttribute("message", "用户注册成功");
            } else {
                request.setAttribute("message", "用户注册失败");
            }
            requestDispatcher = servletContext.getRequestDispatcher("/message.jsp");
            requestDispatcher.forward(request, response);

        }
    }

}
